package com.santiao.youxiang.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import com.gyf.immersionbar.ImmersionBar
import com.santiao.publics.ui.SettingFragment
import com.santiao.youxiang.MainActivity
//import com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
import kotlin.apply
//import kotlin.jvm.java
import com.santiao.youxiang.bean.EmailBean
import com.santiao.youxiang.databinding.ActivityEmailWriteBinding

import com.santiao.youxiang.ext.thrillClickListener
import com.santiao.youxiang.ui.fragment.HomeViewModel
import com.santiao.youxiang.ui.widget.LoadingDiaLog
import com.sun.mail.imap.IMAPFolder
import com.sun.mail.imap.IMAPStore
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.leefeng.promptlibrary.PromptButton
import me.leefeng.promptlibrary.PromptDialog
import java.util.Properties
import javax.mail.Authenticator
import javax.mail.Flags
import javax.mail.Folder
import javax.mail.Message
import javax.mail.MessagingException
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import kotlin.toString

class EmailWriteActivity: AppCompatActivity() {
    private lateinit var binding: ActivityEmailWriteBinding
//    private lateinit var lzyadsUtils: com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
var type_a="" //1 医保 2：社保

    var type=0
    var defaultSubject:String=""
    var defaultAddress:String=""
    lateinit var emailBean:EmailBean

    var slePosition=1

    private lateinit var loadingDiaLog: LoadingDiaLog

    var struri=""
    // 在类顶部定义
    val REQUEST_STORAGE_PERMISSION = 1001  // 可以是任意唯一整数
    private lateinit var HviewModel: HomeViewModel

    companion object {
        // 定义一个静态方法来创建Intent
        // 定义一个静态方法来创建Intent并携带uri数据
        fun startActivity(context: Context?, bundle: Bundle?) {

//            val intent = Intent(context, EmailWriteActivity::class.java).apply {
//
////                putExtra("type", type)
//
//            }
//
//            context!!.startActivity(intent)

            val intent = Intent(context, EmailWriteActivity::class.java)
            if (bundle != null) {
                intent.putExtras(bundle)  // 使用 bundle 传递数据
            }
            context?.startActivity(intent)


        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEmailWriteBinding.inflate(layoutInflater)
        setContentView(binding?.root)
//        type_a= intent.getStringExtra("type").toString()
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .transparentNavigationBar()
            .init()
        initViews(/*type_a*/)

        SettingFragment.adLoad3(0,null,null,this,this)
    }



     fun initViews(/*type: String*/) {
//        initad()

         type=intent.getIntExtra("type",0)

         if (type==1){
             emailBean=intent.getSerializableExtra("email") as EmailBean
             defaultSubject=emailBean.subject/*intent?.getStringExtra("subject")?:""*/
             defaultAddress=emailBean.toName/*intent?.getStringExtra("address")?:""*/

             binding.editSubject.setText("$defaultSubject")
             binding.editSubject.isEnabled=false
             binding.editAddress.setText(defaultAddress)
             binding.editAddress.isEnabled=false
//             binding.editContent.setText(emailBean.content)
         }

         HviewModel= MainActivity.HviewModel

         initclick()


        binding.toolbarBack.thrillClickListener {
            val promptDialog = PromptDialog(this@EmailWriteActivity);
            val cancel = PromptButton("取消", null)
            cancel.textColor = Color.parseColor("#0076ff")
            cancel.textSize=16f
            val quit= PromptButton("不保存退出") {
                finish()
            }
            val keep= PromptButton("存入草稿箱"){
                val currentPost=
                    HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
                if (currentPost!=null) {
                    if (binding.editAddress.text.isNotBlank()&&binding.editSubject.text.isNotBlank()&&binding.editContent.text.isNotBlank()){
                        saveToTheKeep(currentPost.pAddress,binding.editAddress.text.toString(),binding.editSubject.text.toString(),binding.editContent.text.toString(),currentPost.pCode)
                    }else
                        Toast.makeText(this@EmailWriteActivity,"请填写完整的邮件信息！",Toast.LENGTH_SHORT).show()
                }
            }
            cancel.textSize=16f
            quit.textSize=16f
            keep.textSize=16f
            keep.textColor=Color.RED
            promptDialog.showAlertSheet(
                "", true, cancel,
                quit,
                keep
            )

        }





    }

    fun initclick(){

//        binding.llQq.thrillClickListener {
//            AddAccountActivity.startActivity(this,"1")
//        }

        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val promptDialog = PromptDialog(this@EmailWriteActivity);
                val cancel = PromptButton("取消", null)
                cancel.textColor = Color.parseColor("#0076ff")
                cancel.textSize=16f
                val quit= PromptButton("不保存退出") {
                    finish()
                }
                val keep= PromptButton("存入草稿箱"){
                    val currentPost=
                        HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
                    if (currentPost!=null) {
                        if (binding.editAddress.text.isNotBlank()&&binding.editSubject.text.isNotBlank()&&binding.editContent.text.isNotBlank()){
                            if (type==1){
                                editDraft(currentPost.pAddress,binding.editAddress.text.toString(),binding.editSubject.text.toString(),binding.editContent.text.toString(),currentPost.pCode,emailBean.uid)

                            }else
                            saveToTheKeep(currentPost.pAddress,binding.editAddress.text.toString(),binding.editSubject.text.toString(),binding.editContent.text.toString(),currentPost.pCode)
                        }else
                            Toast.makeText(this@EmailWriteActivity,"请填写完整的邮件信息！",Toast.LENGTH_SHORT).show()
                    }
                }
                cancel.textSize=16f
                quit.textSize=16f
                keep.textSize=16f
                keep.textColor=Color.RED
                promptDialog.showAlertSheet(
                    "", true, cancel,
                    quit,
                    keep
                )
            }
        })

        loadingDiaLog=LoadingDiaLog(this@EmailWriteActivity,"发送中...")
        binding.editAddress.onFocusChangeListener =
            View.OnFocusChangeListener { v, hasFocus ->
                if (!hasFocus) {
                    if (binding.editAddress.text.isNullOrBlank()) {
                        Toast.makeText(
                            this@EmailWriteActivity,
                            "输入邮件地址不能为空！",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        val emailPattern =
                            "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:qq\\.com|126\\.com|163\\.com|aliyun\\.com|gmail\\.com|yahoo\\.com|hotmail\\.com|outlook\\.com|icloud\\.com|sina\\.com|sohu\\.com|live\\.com|mail\\.ru|yandex\\.ru|protonmail\\.com)$"
                        val currentText = binding.editAddress.text.toString()
                        // 如果输入不符合邮件格式，可以做提示或其他处理
                        if (!currentText.matches(emailPattern.toRegex())) {
                            Toast.makeText(
                                this@EmailWriteActivity,
                                "请输入支持的邮件地址！",
                                Toast.LENGTH_SHORT
                            ).show()
                            binding.editAddress.setText("")
                        }
                    }
//                    updateButtonState()
                }
            }
        binding.editAddress.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (binding.editAddress.text.isNullOrBlank()) {
                    Toast.makeText(
                        this@EmailWriteActivity,
                        "输入邮件地址不能为空！",
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    val emailPattern =
                        "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:qq\\.com|126\\.com|163\\.com|aliyun\\.com|gmail\\.com|yahoo\\.com|hotmail\\.com|outlook\\.com|icloud\\.com|sina\\.com|sohu\\.com|live\\.com|mail\\.ru|yandex\\.ru|protonmail\\.com)$"
                    val currentText = binding.editAddress.text.toString()
                    // 如果输入不符合邮件格式，可以做提示或其他处理
                    if (!currentText.matches(emailPattern.toRegex())) {
                        Toast.makeText(
                            this@EmailWriteActivity,
                            "请输入支持的邮件地址！",
                            Toast.LENGTH_SHORT
                        ).show()
                        binding.editAddress.setText("")
                    }
                }
//                updateButtonState()
            }
            false
        }
        //name
        binding.editSubject.onFocusChangeListener =
            View.OnFocusChangeListener { v, hasFocus ->
                if (!hasFocus) {
//                    updateButtonState()
                }
            }
        binding.editSubject.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
//                updateButtonState()
            }
            false
        }
        //name
        binding.editContent.onFocusChangeListener =
            View.OnFocusChangeListener { v, hasFocus ->
                if (!hasFocus) {
//                    updateButtonState()
                }
            }
        binding.editContent.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
//                updateButtonState()
            }
            false
        }
        binding.send.thrillClickListener {
            val currentPost=
                HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
            if (currentPost!=null) {
                sendEmail(currentPost.pAddress,binding.editAddress.text.toString(),binding.editSubject.text.toString(),binding.editContent.text.toString(),currentPost.pCode)
            }
        }








    }

    fun switchItem(position: Int) {

    }

    fun   initad() {
//        myContext = requireContext()
//        lzyadsUtils=
//            com.lazyliuzy.commonui.utils.lzy.LZYADSUtils("Task1Activity", this@Task1Activity)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.loadSimpleAd1(com.lazyliuzy.commonui.databinding.ActivityTask1Binding.flAd)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.showAdCpTurn()

    }

    @OptIn(DelicateCoroutinesApi::class)
    fun saveToTheKeep(from: String, to: String, subject: String, body: String, authCode: String){
        val loadingDiaLog= LoadingDiaLog(this@EmailWriteActivity,"保存中...")
        loadingDiaLog.show()
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = from.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                val message = MimeMessage(session)
                message.setFrom(InternetAddress(from))
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
                message.subject = subject
                message.setContent( """
                    <html>
                        <head>
                            <style>
                            </style>
                        </head>
                        <body>
                            <p>$body</p>
                        </body>
                        </html>
                    """, "TEXT/HTML; charset=UTF-8"
                )
                val store = session.getStore("imaps")
                store.connect(imapHost, from, authCode)
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${from}" // 是一个邮箱
                store.id(idMap)
                val sentFolder = store.getFolder(if (domain=="qq.com") "Drafts" else if (domain=="imap.aliyun.com")  "草稿"  else "草稿箱")
                if (!sentFolder.exists()) sentFolder.create(Folder.HOLDS_MESSAGES)
                sentFolder.open(Folder.READ_WRITE)
                message.setFlag(Flags.Flag.SEEN, true)
                sentFolder.appendMessages(arrayOf(message))
                sentFolder.close(false)
                store.close()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EmailWriteActivity, "保存至草稿箱成功~", Toast.LENGTH_SHORT).show()
                    finish()
                }
            }catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EmailWriteActivity, "保存至草稿箱失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun sendEmail(from: String, to: String, subject: String, body: String, authCode: String) {
        loadingDiaLog.show()
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? = null
            var smtpHost: String? = null
            val domain = from.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                    smtpHost = "smtp.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                    smtpHost = "smtp.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                    smtpHost = "smtp.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                    smtpHost = "smtp.aliyun.com"
                }
            }
            val properties = Properties()
            properties["mail.smtp.host"] = smtpHost
            properties["mail.smtp.port"] = "465" // SSL
            properties["mail.smtp.auth"] = "true"
            properties["mail.smtp.ssl.enable"] = "true"
            val session = Session.getInstance(properties, object : Authenticator() {
                override fun getPasswordAuthentication(): PasswordAuthentication {
                    return PasswordAuthentication(from, authCode) // 使用授权码
                }
            })
            try {
                val message = MimeMessage(session)
                message.setFrom(InternetAddress(from))
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
                message.subject = subject
                message.setContent( """
                    <html>
                    <head>
                        <style>
                        </style>
                    </head>
                    <body>
                        <p>$body</p>
                    </body>
                    </html>
                """, "TEXT/HTML; charset=UTF-8"
                )
                Transport.send(message)
                val store = session.getStore("imaps")
                store.connect(imapHost, from, authCode)
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${from}" // 是一个邮箱
                store.id(idMap)
                val sentFolder = store.getFolder(if (domain=="qq.com") "Sent Messages" else "已发送")
                if (!sentFolder.exists()) sentFolder.create(Folder.HOLDS_MESSAGES)
                sentFolder.open(Folder.READ_WRITE)
                message.setFlag(Flags.Flag.SEEN, true)
                sentFolder.appendMessages(arrayOf(message))
                sentFolder.close(false)
                store.close()
                withContext(Dispatchers.Main) {
                    if (HviewModel.currentEmailType.value==2) {
                        if (type == 1)
                            HviewModel.refreshEmail.value = 2
                        else
                            HviewModel.refreshEmail.value = 1
                    }
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EmailWriteActivity,"发送邮件成功~", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: MessagingException) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EmailWriteActivity,"发送邮件失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun editDraft(from: String, to: String, subject: String, body: String, authCode: String, draftUid: Long) {
        val loadingDiaLog = LoadingDiaLog(this@EmailWriteActivity, "更新草稿中...")
        loadingDiaLog.show()

        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? = null
            val domain = from.substringAfter("@")
            when (domain) {
                "126.com" -> imapHost = "imap.126.com"
                "163.com" -> imapHost = "imap.163.com"
                "qq.com" -> imapHost = "imap.qq.com"
                else -> imapHost = "imap.aliyun.com"
            }
            val imapPort = "993"
            val properties = Properties().apply {
                this["mail.store.protocol"] = "imaps"
                this["mail.imaps.host"] = imapHost
                this["mail.imaps.port"] = imapPort
            }

            val session = Session.getInstance(properties)
            try {
                val store = session.getStore("imaps")
                store.connect(imapHost, from, authCode)

                // 获取草稿箱文件夹
                val draftsFolder = store.getFolder("Drafts") as IMAPFolder
                draftsFolder.open(Folder.READ_WRITE)

                // 获取要编辑的草稿邮件
                val message = draftsFolder.getMessageByUID(draftUid)

                // 删除原始草稿邮件
                message.setFlags(Flags(Flags.Flag.DELETED), true)
                draftsFolder.expunge()

                // 创建新的邮件
                val newMessage = MimeMessage(session)
                newMessage.setFrom(InternetAddress(from))
                newMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
                newMessage.subject = subject
                newMessage.setContent("""
                <html>
                    <head>
                        <style>
                        </style>
                    </head>
                    <body>
                        <p>$body</p>
                    </body>
                </html>
            """, "TEXT/HTML; charset=UTF-8")

                // 保存新邮件为草稿
                val sentFolder = store.getFolder("Drafts") as IMAPFolder
                sentFolder.appendMessages(arrayOf(newMessage))

                draftsFolder.close(false)
                store.close()

                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EmailWriteActivity, "草稿更新成功~", Toast.LENGTH_SHORT).show()
                    finish()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@EmailWriteActivity, "更新草稿失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }



}